#coding=utf-8
#这个文件主要是实现IMAP文件检索，以及SMTP文件发送
import os
import imaplib
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import re

import account

FROM=account.smtpmailbox
TO=account.mailbox
class eximap(imaplib.IMAP4):
    def __init__(self,host):
        imaplib.IMAP4.__init__(self,host)
    def getdirs(self,path):
        dirs=self.list(path)
        if dirs[0]=='OK':
            result=[]
            for x in dirs[1]:
                _dir=re.search(r"""(?<=%s/).+?(?=")""" % path, x)
                if _dir!=None:
                    result.append(_dir.group())
        if len(result)>0:
            return result
    def listfile(self,path='INBOX'):
        '''列出收件箱邮件主题'''
        maillist=[]
        typ,data=self.select(path)
        print u'共有邮件 :', data[0]
        if data[0]!='0':
            typ,data=self.fetch('1:*',account.maillist)
        else:
            return maillist
        for x in data:
            if type(x)==tuple:
                ss=x[0].split()
                n=ss[0]
                m=x[1][9:-4]
                if m[0:2]=='??':
                    s=m[2:].split('??')
                    s.append(str(n))   #保存对应的邮件编号
                    maillist.append(s)
        return maillist  #返回符合标准的文件列表
    def download(self,n):
        '''不要显示结果，太长了，程序会死掉'''
        result=self.fetch(n,account.maildownload)
        return result[1][0][1]

class filesender(smtplib.SMTP):
    '''实现单个文件发送'''
    def __init__(self, host=None, port=None, local_hostname=None):
        smtplib.SMTP.__init__(self, host, port, local_hostname)
    def sendfile(self,path,type):
        '''使用前必须连接，登录'''
        size=os.path.getsize(path)
        moditime=os.path.getmtime(path)
        p,filename=os.path.split(path)
        outmail=MIMEMultipart()
        outmail['Subject']='??file??%s??%d??%d??%s' % (type,size,moditime,filename)
        outmail['From']=FROM
        outmail['TO']=TO
        fp=open(path,'rb')
        msg=MIMEBase('application','octet-stream')
        msg.set_payload(fp.read())
        fp.close()
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        encoders.encode_base64(msg)
        outmail.attach(msg)
        mailobj=outmail.as_string()
        self.sendmail(FROM,TO,mailobj)

if __name__=='__main__':
    s=filesender(account.mailsmtp)
    s.login(account.mailuser,account.mailpass)
    s.sendfile('g:/中文软件.zip', 'doc')
